package cn.jeeweb.web.modules.sys.controller;

import cn.jeeweb.common.http.Response;
import cn.jeeweb.common.mvc.annotation.ViewPrefix;
import cn.jeeweb.common.mvc.controller.BaseBeanController;
import cn.jeeweb.common.mybatis.mvc.wrapper.EntityWrapper;
import cn.jeeweb.common.utils.FastJsonUtils;
import cn.jeeweb.common.utils.StringUtils;
import cn.jeeweb.web.aspectj.annotation.Log;
import cn.jeeweb.web.modules.sys.Constants;
import cn.jeeweb.web.modules.sys.entity.*;
import cn.jeeweb.web.modules.sys.service.*;
import cn.jeeweb.web.utils.UserUtils;
import cn.xjzn.framework_Core.ModuleActionType;
import cn.xjzn.framework_Core.ModuleServe;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;


/**
 *
 */
@RestController
@RequestMapping("/ui/packageinfo")
@ViewPrefix("modules/UipackageInfo")
//@RequiresPathPermission("ui:packageinfo")
@Log(title = "ui_packageinfo")
public class UiPackageInfoController extends BaseBeanController<UiPackageInfo> {
    @Autowired
    IUiPackageInfoService uiPackageInfoService;

    @Autowired
    IUiPropertyService uiPropertyService;

    @Autowired
    IUiControlruleService uiControlruleService;

    @Autowired
    IDictService dictService;

    @Autowired
    private IDictGroupService dictGroupService;

    @Autowired
    private IUiActionButtonService uiActionButtonService;

    @Autowired
    private IUserRoleService userRoleService;

    @PostMapping("add")
    @Log(logType = ModuleActionType.INSERT)
//	@RequiresMethodPermissions("add")
    public Response add(UiPackageInfo entity, BindingResult result,
                        HttpServletRequest request, HttpServletResponse response) {
        // 验证错误
        this.checkError(entity, result);
        uiPackageInfoService.insert(entity);
        return Response.ok("添加成功");
    }

    @PostMapping("{id}/update")
    @Log(logType = ModuleActionType.UPDATE)
//	@RequiresMethodPermissions("update")
    public Response update(UiPackageInfo entity, BindingResult result,
                           HttpServletRequest request, HttpServletResponse response) {
        // 验证错误
        this.checkError(entity, result);
        uiPackageInfoService.insertOrUpdate(entity);
        return Response.ok("更新成功");
    }

    @PostMapping("{id}/delete")
    @Log(logType = ModuleActionType.DELETE)
//	@RequiresMethodPermissions("delete")
    public Response delete(@PathVariable("id") String id) {
        uiPackageInfoService.deleteById(id);
        return Response.ok("删除成功");
    }

    /**
     * @throws IOException
     */
    @RequestMapping(value = "getList", method = {RequestMethod.GET, RequestMethod.POST})
    @Log(logType = ModuleActionType.SELECT)
//	@RequiresMethodPermissions("list")
    public void ajaxList(String...ids) throws IOException {
        List<UiPackageInfo> lists = uiPackageInfoService.getList(new UiPackageInfo());
        //List<UiPackageInfo> uiPackageInfos = uiPackageInfoService.getList(uiPackageInfo);
        List<String> coll=  Arrays.asList(ids);
        List<UiPackageInfo> uiPackageInfos = uiPackageInfoService.selectBatchIds(coll);
        if (uiPackageInfos != null && uiPackageInfos.size() > 0) {
            for (UiPackageInfo bean : uiPackageInfos) {
                initUiPackageInfoChild(bean, lists);
            }
        }
        FastJsonUtils.print(uiPackageInfos);
    }

    public void initUiPackageInfoChild(UiPackageInfo uiPackageInfo, List<UiPackageInfo> lists) {
        //初始化子包集合
        if (uiPackageInfo.getItems() == null) {
            List<UiPackageInfo> items = new ArrayList<UiPackageInfo>();
            uiPackageInfo.setItems(items);
        }
        //初始化字段属性集合
        if (uiPackageInfo.getPropertyInfos() == null) {
            List<UiProperty> properties = new ArrayList<UiProperty>();
            uiPackageInfo.setPropertyInfos(properties);
        }
        //初始化按钮集合
        if (uiPackageInfo.getActionButtons() == null) {
            List<UiActionButton> uiActionButtons = new ArrayList<UiActionButton>();
            uiPackageInfo.setActionButtons(uiActionButtons);
        }
        List<UiProperty> uiPropertiesFromDB = uiPropertyService.getUiPropertiesFromDB(uiPackageInfo.getId());
        List<Dict> dicts = dictService.selectDictList();
        if (uiPropertiesFromDB != null && uiPropertiesFromDB.size() > 0) {
            for (UiProperty bean : uiPropertiesFromDB) {
                if (bean.getControlType() == 1 && !StringUtils.isEmpty(bean.getDictCode())) {
                    bean.setDictItems(getDictsByGid(bean.getDictCode(), dicts));
                }
                if (bean.getHasRule() == 1 && !StringUtils.isEmpty(bean.getControlRule())) {
                    String[] array = bean.getControlRule().split("\\|");
//                    UiControlRule param = new UiControlRule();
//                    param.setIds(array);
//                    bean.setControlRules(uiControlruleService.getList(param));
                    bean.setControlRules(uiControlruleService.selectBatchIds(Arrays.asList(array)));
                }
            }
        }

        List<UiProperty> defaultUiPropertys = uiPropertyService.getUiPropertiesFromEntity(uiPackageInfo.getId());
        if (defaultUiPropertys != null) {
            if (uiPropertiesFromDB != null && uiPropertiesFromDB.size() > 0) {
                uiPropertiesFromDB.forEach(t -> {
                    defaultUiPropertys.removeIf(r -> r.getOwnerPropertyName().equals(t.getOwnerPropertyName()) && r.getPropertyName().equals(t.getPropertyName()));
                });
            }
            assert uiPropertiesFromDB != null;
            defaultUiPropertys.addAll(uiPropertiesFromDB);
            //集合排序
            defaultUiPropertys.sort(Comparator.comparing(UiProperty::getDisplayPosition));
            //List<UiProperty> defaultUiPropertys__=defaultUiPropertys.stream().sorted(t -> t.getDisplayPosition()).collect(Collectors.toList());
            uiPackageInfo.setPropertyInfos(defaultUiPropertys);
        }

        UiActionButton param = new UiActionButton();
        param.setPackageId(uiPackageInfo.getId());
        List<UiActionButton> uiActionButtons = uiActionButtonService.getList(param);
        List<UiActionButton> defaultActionButtons = new ArrayList<UiActionButton>();
        ModuleServe moduleServe = ModuleServe.getEnumByValue(uiPackageInfo.getModuleId());
        if (moduleServe != null) {
            ModuleActionType[] moduleActionTypes = moduleServe.getActions();
            if (moduleActionTypes != null && moduleActionTypes.length > 0) {
                String custom1 = ModuleActionType.CUSTOM1.toString();
                String custom2 = ModuleActionType.CUSTOM2.toString();
                String custom3 = ModuleActionType.CUSTOM3.toString();
                for (int i = 0; i < moduleActionTypes.length; i++) {
                    String actionType = moduleActionTypes[i].toString();
                    if(!ModuleActionType.SELECT.name().equals(actionType) && !custom1.equals(actionType)  && !custom2.equals(actionType)  && !custom3.equals(actionType)){
                        UiActionButton uiActionButton = new UiActionButton();
                        uiActionButton.setCode(moduleActionTypes[i].toString());
                        uiActionButton.setText(moduleActionTypes[i].getName());
                        uiActionButton.setModuleId(uiPackageInfo.getModuleId());
                        uiActionButton.setPackageId(uiPackageInfo.getId());
                        uiActionButton.setSort(moduleActionTypes[i].getSort());
                        defaultActionButtons.add(uiActionButton);
                    }
                }
            }
        }
        if (uiActionButtons != null && uiActionButtons.size() > 0) {
            for (UiActionButton uiActionButton : uiActionButtons) {
                if (StringUtils.isNotBlank(uiActionButton.getControlRule())) {
                    String[] array = uiActionButton.getControlRule().split("\\|");
//                    UiControlRule uiControlRule = new UiControlRule();
//                    uiControlRule.setIds(array);
//                    uiActionButton.setControlRules(uiControlruleService.getList(uiControlRule));
                    uiActionButton.setControlRules(uiControlruleService.selectBatchIds(Arrays.asList(array)));
                }
        }
        }
        if (defaultActionButtons.size() > 0) {
            if (uiActionButtons != null && uiActionButtons.size() > 0) {
                uiActionButtons.forEach(t -> {
                    defaultActionButtons.removeIf(r -> r.getPackageId().equals(t.getPackageId()) && r.getCode().equals(t.getCode()));
                });
            }
            defaultActionButtons.addAll(uiActionButtons);
            defaultActionButtons.sort(Comparator.comparing(UiActionButton::getSort));
            //在此对按钮进行特殊处理 目前只有在操作申请信息里需要进行处理
            String roleId = "";
            User currentUser = UserUtils.getUser();
            EntityWrapper<UserRole> entityWrapper = new EntityWrapper<>(UserRole.class);
            entityWrapper.eq("userId",currentUser.getId());
            List<UserRole> userRoleList = userRoleService.selectList(entityWrapper);
            if(userRoleList != null && userRoleList.size() > 0){
                roleId = userRoleList.get(0).getRoleId();
            }
            if("5002301".equals(uiPackageInfo.getId())){
                if(Constants.AUDIT_ROLE.equals(roleId)){
                    UiActionButton uiActionButton = new UiActionButton();
                    uiActionButton.setCode(ModuleActionType.AUDITOPERATEAPPLY.toString());
                    uiActionButton.setText(ModuleActionType.AUDITOPERATEAPPLY.getName());
                    uiActionButton.setActionCode(Constants.AUDITOPERATEAPPLY);
                    uiActionButton.setModuleId(uiPackageInfo.getModuleId());
                    uiActionButton.setPackageId(uiPackageInfo.getId());
                    uiActionButton.setSort(ModuleActionType.AUDITOPERATEAPPLY.getSort());
                    defaultActionButtons.add(uiActionButton);
                }else if(Constants.STOREMAN_ROLE.equals(roleId)){
                    UiActionButton uiActionButton = new UiActionButton();
                    uiActionButton.setCode(ModuleActionType.BELAIDUP.toString());
                    uiActionButton.setText(ModuleActionType.BELAIDUP.getName());
                    uiActionButton.setModuleId(uiPackageInfo.getModuleId());
                    uiActionButton.setPackageId(uiPackageInfo.getId());
                    uiActionButton.setSort(ModuleActionType.BELAIDUP.getSort());

                    UiActionButton uiActionButton_ = new UiActionButton();
                    uiActionButton_.setCode(ModuleActionType.OUTOFSTOCK.toString());
                    uiActionButton_.setText(ModuleActionType.OUTOFSTOCK.getName());
                    uiActionButton_.setModuleId(uiPackageInfo.getModuleId());
                    uiActionButton_.setPackageId(uiPackageInfo.getId());
                    uiActionButton_.setSort(ModuleActionType.OUTOFSTOCK.getSort());

                    UiActionButton uiActionButtonRepair = new UiActionButton();
                    uiActionButtonRepair.setCode(ModuleActionType.REPAIR.toString());
                    uiActionButtonRepair.setText(ModuleActionType.REPAIR.getName());
                    uiActionButtonRepair.setModuleId(uiPackageInfo.getModuleId());
                    uiActionButtonRepair.setPackageId(uiPackageInfo.getId());
                    uiActionButtonRepair.setSort(ModuleActionType.REPAIR.getSort());

                    UiActionButton uiActionButtonScrap = new UiActionButton();
                    uiActionButtonScrap.setCode(ModuleActionType.SCRAP.toString());
                    uiActionButtonScrap.setText(ModuleActionType.SCRAP.getName());
                    uiActionButtonScrap.setModuleId(uiPackageInfo.getModuleId());
                    uiActionButtonScrap.setPackageId(uiPackageInfo.getId());
                    uiActionButtonScrap.setSort(ModuleActionType.SCRAP.getSort());
                    defaultActionButtons.add(uiActionButton_);
                    defaultActionButtons.add(uiActionButton);
                    defaultActionButtons.add(uiActionButtonRepair);
                    defaultActionButtons.add(uiActionButtonScrap);
                }
            }else if("5002501".equals(uiPackageInfo.getId())){
                if(Constants.AUDIT_ROLE.equals(roleId)){
                    UiActionButton uiActionButton = new UiActionButton();
                    uiActionButton.setCode(ModuleActionType.AUDITOPERATEAPPLY.toString());
                    uiActionButton.setText(ModuleActionType.AUDITOPERATEAPPLY.getName());
                    uiActionButton.setActionCode(Constants.AUDITSPAREOPERATEAPPLY);
                    uiActionButton.setModuleId(uiPackageInfo.getModuleId());
                    uiActionButton.setPackageId(uiPackageInfo.getId());
                    uiActionButton.setSort(ModuleActionType.AUDITOPERATEAPPLY.getSort());
                    defaultActionButtons.add(uiActionButton);
                }else if(Constants.STOREMAN_ROLE.equals(roleId)){
                    UiActionButton uiActionButton = new UiActionButton();
                    uiActionButton.setCode(ModuleActionType.SPAREBELAIDUP.toString());
                    uiActionButton.setText(ModuleActionType.SPAREBELAIDUP.getName());
                    uiActionButton.setModuleId(uiPackageInfo.getModuleId());
                    uiActionButton.setPackageId(uiPackageInfo.getId());
                    uiActionButton.setSort(ModuleActionType.SPAREBELAIDUP.getSort());

                    UiActionButton uiActionButton_ = new UiActionButton();
                    uiActionButton_.setCode(ModuleActionType.SPAREOUTOFSTOCK.toString());
                    uiActionButton_.setText(ModuleActionType.SPAREOUTOFSTOCK.getName());
                    uiActionButton_.setModuleId(uiPackageInfo.getModuleId());
                    uiActionButton_.setPackageId(uiPackageInfo.getId());
                    uiActionButton_.setSort(ModuleActionType.SPAREOUTOFSTOCK.getSort());

                    defaultActionButtons.add(uiActionButton_);
                    defaultActionButtons.add(uiActionButton);
                }
            }
            uiPackageInfo.setActionButtons(defaultActionButtons);
        }

        if (uiPackageInfo != null) {
            String subPackageName = uiPackageInfo.getSubPackageName();
            if (subPackageName != null && !"".equals(subPackageName)) {
                String[] array = subPackageName.split("\\|");
                if (array != null && array.length > 0) {
                    if (lists != null && lists.size() > 0) {
                        for (String val : array) {
                            for (UiPackageInfo packageInfo : lists) {
                                if (val.equals(packageInfo.getPropertyName())) {
                                    uiPackageInfo.getItems().add(packageInfo);
                                    initUiPackageInfoChild(packageInfo, lists);
                                }
                            }
                        }
                    }

                }
            }
        }

    }

    public List<Dict> getDictsByGid(String gid, List<Dict> dicts) {
        List<Dict> results = dicts != null ? null : dicts.stream().filter(t -> t.getGid() == gid).collect(Collectors.toList());
        return results;
    }

    public List<Dict> getDictsByCode(String code, List<Dict> dicts) {
        DictGroup search = new DictGroup();
        search.setCode(code);
        DictGroup dictGroup = dictGroupService.getDictGroupByCode(search);
        String gid = "";
        if (!StringUtils.isEmpty(dictGroup.getId())) {
            gid = dictGroup.getId();
        }
        List<Dict> results = new ArrayList<Dict>();
        if (dicts != null && dicts.size() > 0) {
            for (Dict dict : dicts) {
                if (gid.equals(dict.getGid())) {
                    results.add(dict);
                }
            }
        }
        return results;
    }

    @RequestMapping(value = "getModuleServeList", method = {RequestMethod.GET, RequestMethod.POST})
    @Log(logType = ModuleActionType.SELECT)
    public void getModuleServeList() {
        List<ModuleServeBean> list = new ArrayList<ModuleServeBean>();
        ModuleServe[] moduleServe = ModuleServe.values();
        if (moduleServe != null && moduleServe.length > 0) {
            for (int i = 0; i < moduleServe.length; i++) {
                ModuleServeBean module = new ModuleServeBean();
                module.setValue(moduleServe[i].getValue());
                module.setName(moduleServe[i].getName());
                list.add(module);
            }
        }
        FastJsonUtils.print(list);
    }

}